/*
 * Copyright (C) 2007 ETH Zurich
 *
 * This file is part of Fosstrak (www.fosstrak.org).
 *
 * Fosstrak is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software Foundation.
 *
 * Fosstrak is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Fosstrak; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */
package com.qf.cx.simplenms.subscriber.type;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.qf.cx.simplenms.report.model.Report;
import com.qf.cx.simplenms.subscriber.type.exception.InvalidURIException;

/**
 * deliver a message using a file.
 * 
 * @author swieland
 */
public class FileSubscriberOutputChannel extends AbstractSubscriberOutputChannel {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	/** localhost */
	private static final String LOCALHOST = "localhost";

	private URI uri;
	private final String host;
	private final String path;

	public FileSubscriberOutputChannel(String notificationURI) throws InvalidURIException {
		try {
			uri = new URI(notificationURI.replaceAll("\\\\", "/"));
			path = StringUtils.startsWithIgnoreCase(uri.getPath(), "/") ? uri.getPath().substring(1) : uri.getPath();
			if ("".equalsIgnoreCase(path) || StringUtils.endsWithIgnoreCase(path, "/")) {
				throw new InvalidURIException("missing filename");
			}
			host = (uri.getHost() == null) ? LOCALHOST : uri.getHost();
			if (!(LOCALHOST.equalsIgnoreCase(getHost()))) {
				throw new InvalidURIException("This implementation can not write reports to a remote file.");
			}
			if (!("FILE".equalsIgnoreCase(uri.getScheme()))) {
				logger.error("invalid scheme: " + uri.getScheme());
				throw new InvalidURIException("invalid scheme: " + uri.getScheme());
			}
		} catch (URISyntaxException e) {
			logger.error("malformed URI");
			throw new InvalidURIException("malformed URI: ", e);
		}
	}

	@Override
	public boolean push(Report report) {
		writeNotificationToFile(report);
		return true;
	}

	/**
	 * This method writes ec reports to a file.
	 *
	 * @param report
	 *            to write to the file
	 * @throws ImplementationException
	 *             if an implementation exception occures
	 */
	private void writeNotificationToFile(Report report) {
		// append reports as xml to file
		logger.debug("write report '" + report + "' to file '" + getPath() + "'.");

		File file = getFile();

		Date date = new Date(report.getReportCreateTime());
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");

		file = new File(file, report.getTopic() + "-" + df.format(date) + ".json");

		try (FileOutputStream fileOutputStream = new FileOutputStream(file, true);) {
			fileOutputStream.write(getJson(report).getBytes("UTF-8"));
		} catch (IOException e) {
			logger.error("Could not write to file '" + getPath() + "'.", e);
		}
	}

	protected File getFile() {
		return new File(getPath());
	}

	public String getHost() {
		return host;
	}

	public String getPath() {
		return path;
	}

	@Override
	public String toString() {
		return uri.toString();
	}
}
